package com.example.ai.config;


import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;


@Component
public class RedisChatMemory implements ChatMemory {

    private static final String KEY_PREFIX = "chat:memory:";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void add(String conversationId, List<Message> messages) {
        if (messages == null || messages.isEmpty()) {
            return;
        }
        String key = KEY_PREFIX + conversationId;
        // 使用 List 数据结构追加消息
        for (Message message : messages) {
            redisTemplate.opsForList().rightPush(key, message);
        }
    }

    @Override
    public void add(String conversationId, Message message) {
        if (message == null) {
            return;
        }
        String key = KEY_PREFIX + conversationId;
        redisTemplate.opsForList().rightPush(key, message);
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        String key = KEY_PREFIX + conversationId;
        List<Object> range = redisTemplate.opsForList().range(key, -lastN, -1);
        if (range == null || range.isEmpty()) {
            return Collections.emptyList();
        }

        List<Message> messages = new ArrayList<>();
        for (Object obj : range) {
            if (obj instanceof Message message) {
                messages.add(message);
            }
        }
        return messages;
    }

    @Override
    public void clear(String conversationId) {
        String key = KEY_PREFIX + conversationId;
        redisTemplate.delete(key);
    }
}
